package onion.molingo2o.activity.request;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMError;
import com.easemob.chatuidemo.adapter.VoicePlayClickListener;
import com.easemob.chatuidemo.ui.BaseActivity;
import com.easemob.chatuidemo.utils.CommonUtils;
import com.easemob.easeui.ui.EaseBaiduMapActivity;
import com.easemob.util.VoiceRecorder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import onion.molingo2o.Config;
import onion.molingo2o.R;
import onion.molingo2o.activity.MapControlActivity;
import onion.molingo2o.activity.ablumimage.AlbumActivity;
import onion.molingo2o.activity.ablumimage.ImagePagerActivity;
import onion.molingo2o.adapter.OnionAdapter;
import onion.molingo2o.bean.RequestSimple;
import onion.molingo2o.bean.SpeakTemp;
import onion.molingo2o.db.DBHelperManager;
import onion.molingo2o.utils.AddressSelect;
import onion.molingo2o.utils.FileUtils;
import onion.molingo2o.utils.ImageUtils;
import onion.molingo2o.utils.PreferencesUtils;
import onion.molingo2o.utils.SelectImgUtil;
import onion.molingo2o.utils.imageutil.BimpRotateUtil;
import onion.molingo2o.utils.imageutil.BitmapHelper;
import onion.molingo2o.views.MyPopWindow;
import onion.molingo2o.views.MyTempWindow;

/**
 * Created by Administrator on 2015/11/12.
 */
public class NewRequeSendActivity extends BaseActivity {
    SelectImgUtil selectImgUtil;
    /*录音*/
    VoiceRecorder voiceRecorder;
    private ImageView micImage;
    private View mWheelLayout;
    private TextView txt_address;
    PopupWindow mPop;
    private Drawable[] micImages;
    private PowerManager.WakeLock wakeLock;
    private View rootView;
    private int REQUESTLOCATION=1226;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_new_request);
        rootView = findViewById(R.id.rootview);
        initTitle("", "发布新需求", "");
        findViewById(R.id.btn_tosend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toSend();
            }
        });
        ArrayList<SpeakTemp> speakTemps=new ArrayList<>();
        for(int i=0;i<6;i++){
        SpeakTemp speakTemp=new SpeakTemp();
            speakTemp.title="模板"+i;
            speakTemp.content="佳佳基时代的胡搜ID好哦啊大红撒谎冻哈搜都爱上大花洒黄东华山东哈搜湿哒哒shoqednsd sdad asdad";
            speakTemps.add(speakTemp);
        }
        PreferencesUtils.saveTemps(speakTemps);
        selectImgUtil=new SelectImgUtil(this);
        // 动画资源文件,用于录制语音时
        micImages = new Drawable[] { getResources().getDrawable(R.drawable.record_animate_01),
                getResources().getDrawable(R.drawable.record_animate_02),
                getResources().getDrawable(R.drawable.record_animate_03),
                getResources().getDrawable(R.drawable.record_animate_04),
                getResources().getDrawable(R.drawable.record_animate_05),
                getResources().getDrawable(R.drawable.record_animate_06),
                getResources().getDrawable(R.drawable.record_animate_07),
                getResources().getDrawable(R.drawable.record_animate_08),
                getResources().getDrawable(R.drawable.record_animate_09),
                getResources().getDrawable(R.drawable.record_animate_10),
                getResources().getDrawable(R.drawable.record_animate_11),
                getResources().getDrawable(R.drawable.record_animate_12),
                getResources().getDrawable(R.drawable.record_animate_13),
                getResources().getDrawable(R.drawable.record_animate_14) };
        wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "molingO2O");
        voiceRecorder = new VoiceRecorder(micImageHandler);
        micImage= (ImageView) findViewById(R.id.iv_recoder);
        micImage.setOnTouchListener(new PressToSpeakListen());
       TextView textView= (TextView) findViewById(R.id.btn_usetemp);
        /*模板*/
        new MyTempWindow(this,textView,selectImgUtil.editSpeakContent);
/*定位*/
        findViewById(R.id.btn_location).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              Intent intent=  new Intent(NewRequeSendActivity.this, MapControlActivity.class);
                startActivityForResult(intent, REQUESTLOCATION);
            }
        });
        /*城市选择*/
        txt_address= (TextView) findViewById(R.id.txt_address);
        initAddress(null,null,null);

    }
    private void toSend(){
        startActivity(new Intent(this,SendResultActivity.class));
        finish();
    }

    @Override
    protected void onDestroy() {
        BitmapHelper.cleanBitmap();
        super.onDestroy();

    }
    private Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            // 切换msg切换图片
            micImage.setImageDrawable(micImages[msg.what]);
        }
    };
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == AlbumActivity.resultCode_to_NewActivity) {
            if (data != null) {
                selectImgUtil.  refreshGridView();
            }
        } else if (resultCode == ImagePagerActivity.resultCode_to_newAcitivity) {
            selectImgUtil. refreshGridView();
        }
        if (requestCode == SelectImgUtil.requestCode_to_Photo) {
            Log.i("onion", "data" + data);
            String photoName=selectImgUtil.photoName;
            if (data != null) { //可能尚未指定intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                //返回有缩略图
                if (data.hasExtra("data")) {

                    Bitmap thumbnail = data.getParcelableExtra("data");
                    //Bitmap thumbnail= null;
                    try {
                        int degree = BimpRotateUtil.getBitmapDegree(photoName);
                        thumbnail = BimpRotateUtil.rotateBitmapByDegree(thumbnail, degree);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //得到bitmap后的操作
                    FileUtils.saveBitmap(thumbnail, photoName);
                    // FileUtils.saveMyBitmap(photoName,thumbnail );
                    File f = new File(photoName);
                    if (f.exists()) {
                        ImageUtils.rotate(BitmapFactory.decodeFile(photoName), ImageUtils.readPictureDegree(photoName));
                        BitmapHelper.imageListStorage.add(photoName);
                        selectImgUtil.refreshGridView();
                    }
                }
            } else {
                //由于指定了目标uri，存储在目标uri，intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                // 通过目标uri，找到图片
                // 对图片的缩放处理
                // 操作
                ImageUtils.rotate(BitmapFactory.decodeFile(photoName), ImageUtils.readPictureDegree(photoName));
                BitmapHelper.imageListStorage.add(photoName);
                selectImgUtil.refreshGridView();
            }

        }else
        if (requestCode == SelectImgUtil.requestCode_to_imagePager) {
            selectImgUtil.refreshGridView();
        }
        else if (requestCode==REQUESTLOCATION&&resultCode==RESULT_OK){
           double latitude= data.getDoubleExtra(Config.INTENT_latitude,0.0);
            double longitude=   data.getDoubleExtra(Config.INTENT_longitude, 0.0);
         String address=   data.getStringExtra(Config.INTENT_address);
            showToast(latitude+"/"+longitude+"/"+address);
        }
    }
    /**
     * 按住说话listener
     *
     */
    class PressToSpeakListen implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (!CommonUtils.isExitsSdcard()) {
                        String st4 = getResources().getString(R.string.Send_voice_need_sdcard_support);
                        Toast.makeText(NewRequeSendActivity.this, st4, Toast.LENGTH_SHORT).show();
                        return false;
                    }
                    try {
                        v.setPressed(true);
                        wakeLock.acquire();
                        if (VoicePlayClickListener.isPlaying)
                            VoicePlayClickListener.currentPlayListener.stopPlayVoice();
                        voiceRecorder.startRecording(null, "filename", getApplicationContext());
                    } catch (Exception e) {
                        e.printStackTrace();
                        v.setPressed(false);
                        if (wakeLock.isHeld())
                            wakeLock.release();
                        if (voiceRecorder != null)
                            voiceRecorder.discardRecording();
                        Toast.makeText(NewRequeSendActivity.this, R.string.recoding_fail, Toast.LENGTH_SHORT).show();
                        return false;
                    }

                    return true;
                case MotionEvent.ACTION_MOVE: {
                  /*  if (event.getY() < 0) {
                        recordingHint.setText(getString(R.string.release_to_cancel));
                        recordingHint.setBackgroundResource(R.drawable.recording_text_hint_bg);
                    } else {
                        recordingHint.setText(getString(R.string.move_up_to_cancel));
                        recordingHint.setBackgroundColor(Color.TRANSPARENT);
                    }*/
                    return true;
                }
                case MotionEvent.ACTION_UP:
                    v.setPressed(false);
                    if (wakeLock.isHeld())
                        wakeLock.release();
                    if (event.getY() < 0) {
                        // discard the recorded audio.
                        voiceRecorder.discardRecording();

                    } else {
                        // stop recording and send voice file
                        String st1 = getResources().getString(R.string.Recording_without_permission);
                        String st2 = getResources().getString(R.string.The_recording_time_is_too_short);
                        String st3 = getResources().getString(R.string.send_failure_please);
                        try {
                            int length = voiceRecorder.stopRecoding();
                            if (length > 0) {
                                Log.i("onion","存储路径"+voiceRecorder.getVoiceFilePath());
//                                sendVoice(voiceRecorder.getVoiceFilePath(), voiceRecorder.getVoiceFileName(toChatUsername),
//                                        Integer.toString(length), false);
                            } else if (length == EMError.INVALID_FILE) {
                                Toast.makeText(getApplicationContext(), st1, Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getApplicationContext(), st2, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(NewRequeSendActivity.this, st3, Toast.LENGTH_SHORT).show();
                        }

                    }
                    return true;
                default:
                    if (voiceRecorder != null)
                        voiceRecorder.discardRecording();
                    return false;
            }
        }
    }

    /**
     * 地址选择
     * @param proindex
     * @param cityindex
     * @param townindex
     */
    private void initAddress(String proindex, String cityindex, String townindex) {
        mWheelLayout = View.inflate(this, R.layout.wheel_choose_city_three,
                null);
        DBHelperManager dbHelperManager = new DBHelperManager(this);
        if (proindex != null && cityindex != null && townindex != null)
            txt_address.setText(dbHelperManager.getAddressInfo(proindex,
                    cityindex, townindex));
        AddressSelect.initWheelCity(this, mWheelLayout, proindex, cityindex,
                townindex, new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                            case Config.COMPLETE:
                                HashMap<String, String> map = (HashMap) msg.obj;
                                txt_address.setText(map.get(AddressSelect.proName)
                                        + map.get(AddressSelect.cityName)
                                        + map.get(AddressSelect.townName));
                                txt_address.setTag(map);
                                dismissPw();
                                break;
                            case Config.CANCEL:
                                dismissPw();
                                break;
                        }

                    }
                });
        txt_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                showPw(mWheelLayout);
            }
        });
    }

    private void dismissPw() {
        if (mPop != null) {
            mPop.dismiss();
            mPop = null;
        }
    }

    private void showPw(View v) {
        if (mPop == null) {
            mPop = new PopupWindow(v, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            mPop.setOutsideTouchable(false);
            // 设置SelectPicPopupWindow弹出窗体的宽
            mPop.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            // 设置SelectPicPopupWindow弹出窗体的高
            mPop.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
            // mPop.setFocusable(true);
            ColorDrawable dw = new ColorDrawable(0xb0000000);
            // 设置SelectPicPopupWindow弹出窗体的背景
            mPop.setBackgroundDrawable(dw);
//            mPop.setBackgroundDrawable(new BitmapDrawable());
            mPop.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
            mPop.update();
        } else {
            mPop.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);

        }
    }

}
